//获取登录人信息
let login_id;
$(document).ready(function () {
    if (login != undefined) {
        $.ajax({
            type: "get",
            url: "http://localhost:3301/user?phone=" + login,
            async: false,
            success: function (e) {
                login_id = e[0].id;
            }
        })
    }
    let cart_box = $(".cart-body");
    let cart = [];
    if (login_id != undefined) {
        $("#tips-is-login").hide();
        //已登录
        $.ajax({
            type: "get",
            url: "http://localhost:3301/cart?user_id=" + login_id,
            async: false,
            success: function (data) {
                data.forEach((e, i) => {
                    cart.push(e);
                })
            }
        })
    } else {
        //未登录
        cart = JSON.parse(getCookie("cart"));
    }
    cart.forEach((e, i) => {
        let total_price = 0;
        let price = 0;
        let cart_item = $(`<div class="cart-list">
                        <ul class="goods-list yui3-g">
                            <li class="yui3-u-1-24">
                                <input type="checkbox" class="row_check" name="" id="" value="">
                            </li>
                            <li class="yui3-u-6-24">
                                <div class="good-item">
                                    <div class="item-img"><img src="../img/goods.png"></div>
                                    <div class="item-msg">Apple Macbook Air 13.3英寸笔记本电脑 银色（Corei5）处理器/8GB内存
                                    </div>
                                </div>
                            </li>
                            <li class="yui3-u-5-24">
                                <div class="item-txt"></div>
                            </li>
                            <li class="yui3-u-1-8"><span class="price"></span></li>
                            <li class="yui3-u-1-8">
                                <a href="javascript:void(0)" class="increment mins">-</a>
                                <input autocomplete="off" type="text" value="1" minnum="1" class="itxt current_number">
                                <a href="javascript:void(0)" class="increment plus">+</a>
                            </li>
                            <li class="yui3-u-1-8"><span class="sum"></span></li>
                            <li class="yui3-u-1-8">
                                <a href="#none" class="delete">删除</a><br>
                                <a href="#none">移到我的关注</a>
                            </li>
                        </ul>
                    </div>`);
        $.ajax({
            type: "get",
            url: "http://localhost:3301/goods?id=" + e.goods_id,
            async: false,
            success: function (good) {
                let go = good[0];
                cart_item.find(".item-img img").attr("src", go.goods_logo);
                cart_item.find(".item-msg").html(go.goods_name);
                price = parseInt(go.goods_price);
            }
        })
        if (e.spec_goods_id != undefined) {
            $.ajax({
                type: "get",
                url: "http://localhost:3301/spec_goods?id=" + e.spec_goods_id,
                async: false,
                success: function (spec) {
                    let sp = spec[0];
                    cart_item.find(".item-txt").html(sp.value_names);
                    price = parseInt(sp.price);
                }
            })
        }
        cart_item.find(".delete").attr("cart_id", e.id);
        cart_item.find(".row_check").attr("cart_id", e.id);
        cart_item.find(".price").html(price);
        total_price += price * parseInt(e.number);
        cart_item.find(".current_number").attr("cart_id", e.id);
        cart_item.find(".current_number").val(parseInt(e.number));
        cart_box.append(cart_item);
        if (Boolean(parseInt(e.is_selected))) {
            cart_item.find(".row_check").attr("checked", true);
        }
    })
    //-----------------购物车初始化后绑定方法
    calculation();
    function calculation() {
        let total = 0;
        let total_num = 0;
        let goods_num = 0;
        $(".cart-body .cart-list").each((i, e) => {
            let subtotal = 0;
            let price = parseInt($(e).find(".price").html());
            let num = parseInt($(e).find(".current_number").val());
            subtotal = price * num;
            $(e).find(".sum").html(subtotal);

            if ($(e).find(".row_check").prop("checked")) {
                total += subtotal;
                total_num += num;
            }
            goods_num += num;
        })
        $("#total_number").html(total_num);
        $("#total_price").html("￥" + total);
        $(".allgoods h4 span").html(goods_num);

    }
    //商品复是否选中状态修改
    $(".row_check").click(function () {
        let is_selected = $(this).prop("checked") ? 1 : 0;
        if (isLogin() != undefined) {
            let cid = $(this).attr("cart_id");
            $.ajax({
                type: "get",
                url: "http://localhost:3301/cart?id=" + cid,
                success: function (e) {
                    e = e[0];
                    e.is_selected = parseInt(is_selected);
                    $.ajax({
                        type: "put",
                        url: "http://localhost:3301/cart/" + cid,
                        data: e,
                        success: function (e) {
                            console.log("修改了");
                        }
                    })
                }
            })
        } else {
            if (getCookie("cart") != "") {
                let cart = JSON.parse(getCookie("cart"));
                let index = $(this).parent().parent().parent().index();
                cart[index].is_selected = is_selected;
                setCookie("cart", JSON.stringify(cart), 2);
            }
        }
        check_all();
        calculation();
    })
    check_all();
    //判断是否都选中
    function check_all() {
        let flag = true;
        $(".cart-list .row_check").each((i, e) => {
            if (!$(e).prop("checked")) {
                flag = false;
            }
        })
        $(".check_all").prop("checked", flag);
        calculation();
    }
    $(".check_all").click(function () {
        let is_selected = $(this).prop("checked");
        $(".check_all").prop("checked", is_selected);
        $(".row_check").prop("checked", is_selected);
        if (isLogin() != undefined) {
            $.ajax({
                type: "get",
                url: "http://localhost:3301/cart?user_id=" + login_id,
                async: false,
                success: function (data) {
                    data.forEach((e, i) => {
                        e.is_selected = is_selected ? 1 : 0;
                        console.log(e);
                        $.ajax({
                            type: "put",
                            url: "http://localhost:3301/cart/" + e.id,
                            data: e,
                            async: false,
                            success: function (e) {
                                console.log("修改了");
                            }
                        })
                    })
                }
            })
        } else {
            if (getCookie("cart") != "") {
                let cart = [];
                cart = JSON.parse(getCookie("cart"));
                for (var i = 0; i < cart.length; i++) {
                    cart[i].is_selected = is_selected;
                }
                setCookie("cart", JSON.stringify(cart), 2);
            }
        }
        calculation();
    })
    //修改商品数量
    function cartNum(cid, num) {
        if (isLogin() != undefined) {
            $.ajax({
                type: "get",
                url: "http://localhost:3301/cart?id=" + cid,
                success: function (data) {
                    let cart = data[0];
                    cart.number = num;
                    $.ajax({
                        type: "put",
                        url: "http://localhost:3301/cart/" + e.id,
                        data: cart,
                        async: false,
                        success: function (e) {
                            console.log("修改了");
                        }
                    })
                }
            })
        } else {
            if (getCookie("cart") != "") {
                let cart = [];
                cart = JSON.parse(getCookie("cart"));
                cart[cid].number = num;
                setCookie("cart", JSON.stringify(cart), 2);
            }
        }
        calculation();
    }
    $(".cart-list .plus").click(function () {
        let num = $(this).parent().find(".current_number");
        if (isNaN(num.val())) {
            num.val(1);
        }
        if (parseInt(num.val()) >= 10) {
            return;
        }
        num.val(parseInt(num.val()) + 1);
        if (isLogin() != undefined) {
            let cid = num.attr("cart_id");
            cartNum(cid, num.val());
        } else {
            let index = $(this).parent().parent().parent().index();
            cartNum(index, num.val());
        }
        calculation();
    })
    $(".cart-list .mins").click(function () {
        let num = $(this).parent().find(".current_number");
        if (isNaN(num.val())) {
            num.val(1);
        }
        if (parseInt(num.val()) <= 1) {
            return;
        }
        num.val(parseInt(num.val()) - 1);
        console.log($(this));
        if (isLogin() != undefined) {
            let cid = num.attr("cart_id");
            cartNum(cid, num.val());
        } else {
            let index = $(this).parent().parent().parent().index();
            cartNum(index, num.val());
        }
        calculation();
    })
    $(".cart-list .current_number").change(function () {
        if (isNaN(this.value)) {
            $(this).val(1);
        }
        if (isLogin() != undefined) {
            let cid = $(this).attr("cart_id");
            cartNum(cid, $(this).val());
        } else {
            let index = $(this).parent().parent().parent().index();
            cartNum(index, $(this).val());
        }
    })
    //删除事件
    $(".cart-list .delete").click(function () {
        let t = $(this);
        if (isLogin() != undefined) {
            let cid = $(this).attr("cart_id");
            if (confirm("确定要删除吗？")) {
                $.ajax({
                    type: "get",
                    url: "http://localhost:3301/cart?id=" + cid,
                    success: function (data) {
                        let cart = data[0];
                        $.ajax({
                            type: "delete",
                            url: "http://localhost:3301/cart/" + cart.id,
                            success: function (data) {
                                t.parent().parent().parent().remove();
                            }
                        })
                        //删除后的商品添加到本地cookie
                        setCookie("delete-cart", JSON.stringify(cart), 7);
                    }
                })
            }
        } else {
            let cart = JSON.parse(getCookie("cart"));
            let index = $(this).parent().parent().parent().index();
            let new_cart = [];
            for(let i=0;i<cart.length;i++){
                if(i==index){
                    continue;
                }
                new_cart.push(cart[i]);
            }
            setCookie("cart", JSON.stringify(new_cart), 2);
            $(this).parent().parent().parent().remove();
        }
    })
    $(".sum-btn").click(function(){
        if($("#total_number").html()=="0"){
            alert("请选中需要结算的商品");
            return false;
        }
    })
})